<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="dataForm.roleName" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item size="mini" label="授权">
        <el-tree :data="permissionList" :props="permissionListTreeProps" node-key="menuId" ref="permissionListTree"
          :default-expand-all="false" show-checkbox>
        </el-tree>
      </el-form-item>

      <el-form-item size="mini" label="菜单">
        <el-tree :data="menuList" :props="menuListTreeProps" node-key="menuId" ref="menuListTree"
          :default-expand-all="false" show-checkbox>
        </el-tree>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { roleApi, userApi } from '@/api/user'
import { treeDataToList,clone } from '@/utils'
import { is } from 'type-is'
export default {
  data() {
    return {
      visible: false,
      menuList: [],
      menuListTreeProps: {
        label: 'name',
        children: 'list'
      },
      permissionList: [],
      permissionListTreeProps: {
        label: 'name',
        children: 'list'
      },
      dataForm: {
        id: 0,
        roleName: '',
        remark: ''
      },
      dataRule: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    }
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0
      userApi.menuListTree().then(({ data }) => {
        this.permissionList = data
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.$refs.permissionListTree.setCheckedKeys([])
        })
      }).then(() => {
        userApi.menuSelected().then(({ data }) => {
          this.menuList = data


        })
      }).then(() => {
        if (this.dataForm.id) {
          roleApi.getInfo(this.dataForm.id).then(({ role }) => {
            this.dataForm.roleName = role.roleName
            this.dataForm.remark = role.remark
            var idx = role.menuIdList.indexOf(this.tempKey)
            if (idx !== -1) {
              role.menuIdList.splice(idx, role.menuIdList.length - idx)
            }
            //排除选中的父节点
            let menulist = treeDataToList(JSON.parse(JSON.stringify(this.menuList)))
            let rolemenu = clone(role.menuIdList)
            for(let i in rolemenu){
              for(let m of menulist){
                if(rolemenu[i] == m['parentId']){
                  rolemenu.splice(i,1)
                }
              }
            }

            this.$refs.menuListTree.setCheckedKeys(rolemenu)
            let menuList = treeDataToList(JSON.parse(JSON.stringify(this.menuList)))
            let permisstions = this.excludeMenu(role.menuIdList, menuList)
            this.$refs.permissionListTree.setCheckedKeys(permisstions)

          })
        }
      })
    },
    /**
     * 排除数组指定数据
     * @param {*} souce 源数据
     * @param {*} exclude 需要排除数据
     * */
    excludeMenu(souce = [], exclude = []) {
      let souceData = []


      for (let menuId of souce) {
        let inExclude = false;
        for (let menu of exclude) {
          if (menuId == menu['menuId']) {
            inExclude = true;
            break;
          }
        }
        if (!inExclude) {
          souceData.push(menuId)
        }
      }

      return souceData
    },
    // 表单提交


    dataFormSubmit() {
      //获取选中权限列表 排除选中菜单
      let permisstions = [].concat(this.$refs.permissionListTree.getCheckedKeys())

      let AllmenuList = treeDataToList(JSON.parse(JSON.stringify(this.menuList)))

      permisstions = this.excludeMenu(permisstions, AllmenuList)


      // }
      //表单数据
      let formData = {
        'roleId': this.dataForm.id || undefined,
        'roleName': this.dataForm.roleName,
        'remark': this.dataForm.remark,
        'menuIdList': [].concat(permisstions, this.$refs.menuListTree.getCheckedKeys() ,this.$refs.menuListTree.getHalfCheckedKeys()).sort()
      }
      formData = JSON.parse(JSON.stringify(formData))
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          roleApi.savrOrUpdateRole(formData, !this.dataForm.id ? 'save' : 'update').then(({ data }) => {

            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })

          })
        }
      })
    }
  }
}
</script>
